import { reqRegister, reqUserLogin,reqUserInfo,} from "@/api"

const actions = {
    async registerUser({ commit, state, dispatch }, obj) {
        //注册接口没有返回data,不需要提交mutation 
        const username = obj.username2
        const password = obj.password2
        // console.log(username,password)
        let result = await reqRegister({username,password});
        if (result.isregister) {
             //注册成功
             return 'ok';
        } else {
             //注册失败
             return Promise.reject(new Error(result.errormessage));
        }
   },
   async userLogin({commit, state, dispatch},data){
    console.log(data)
    let result = await reqUserLogin(data);
    if(result.islogin){
        commit('SET_TOKEN', result.token);
        console.log(result.token)
        localStorage.setItem('token', result.token);
        return 'ok';
    }else{
        return Promise.reject(new Error(result.message));
    }
   },
   async getUserInfo({ commit, state, dispatch }) {
    let result = await reqUserInfo();
    if (result.data) {
        console.log(result)
        console.log('aaa')
         commit('SET_USERINFO', result);
         return 'ok';
    } else {
         return Promise.reject();
        }
    },
    async logout({ commit, state, dispatch }) {
        //发请求通知服务器销毁当前token
        // let result = await reqUserLogout();
            // console.log(result)
             commit('CLEAR');
             return 'ok';
   }
}
const mutations = {
    SET_TOKEN(state, token) {
        state.token = token;
   },
   SET_USERINFO(state, username) {
    state.nickName = nickName;
    },
    CLEAR(state) {
        //清除仓库相关用户信息
        state.token = '';
        // state.nickName = '';
        //本地存储令牌清空
        localStorage.removeItem('token');
   }
}
const state = {
    token:localStorage.getItem("token"),
    nickName:''
}
const getters = {
}

export default{
    actions,
    mutations,
    state,
    getters
}